﻿using CommunityToolkit.Mvvm.Messaging;
using Renci.SshNet;
using SSHTool.Core.Message;
using SSHTool.Model;
using SSHTool.Util;
using SSHTool.ViewModel;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Timers;

namespace SSHTool.Service
{
    public class SshService : IDisposable
    {
        private SshClient sshClient;
        private SftpClient ftpClient;
        private Timer timer;
        private int totalSencod = 0;

        private ConcurrentDictionary<string, List<string>> nameMap = new ConcurrentDictionary<string, List<string>>();

        public string Code { get; set; }

        public string CdCmd { get; set; }

        public void Connect(ConnectionViewModel model)
        {
            try
            {
                InitTimer();

                sshClient = new SshClient(model.Host, model.Port, model.UserName, model.Password);
                sshClient.Connect();

                ftpClient = new SftpClient(model.Host, model.Port, model.UserName, model.Password);
                ftpClient.Connect();
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error($"连接失败 - {model.Port}");
                LogUtil.Instance.Error(ex);
            }
        }

        public void Disconnect()
        {
            sshClient?.Disconnect();
        }

        #region sftp
        public string GetContent(string remotePath, Encoding encoding = null)
        {
            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }

                return ftpClient.ReadAllText(remotePath, encoding);
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error(ex);
                return null;
            }
        }

        public void WriteContent(string remotePath, string content, Encoding encoding = null)
        {
            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }

                ftpClient.WriteAllText(remotePath, content, encoding);
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error(ex);
            }
        }

        public string[] GetAllLines(string remotePath, Encoding encoding = null)
        {
            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }

                return ftpClient.ReadAllLines(remotePath, encoding);
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error(ex);
                return null;
            }
        }

        public void WriteAllLines(string remotePath, List<string> lineList, Encoding encoding = null)
        {
            try
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }

                ftpClient.WriteAllLines(remotePath, lineList, encoding);
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error(ex);
            }
        }

        #endregion

        /// <summary>
        /// 运行命令 有个问题,运行的命令始终都是在默认目录下运行的
        /// 无法切换目录
        /// 只能 cd /具体目录 && 其他命令 这样执行
        /// </summary>
        /// <param name="cmd">命令</param>
        /// <param name="showMsg">输出是否显示在屏幕上</param>
        /// <returns></returns>
        public bool Run(string cmd, bool showMsg = true)
        {
            if (string.IsNullOrEmpty(cmd))
            {
                return false;
            }

            if (sshClient == null)
            {
                return false;
            }

            cmd = cmd.Trim();

            try
            {
                totalSencod = 0;
                timer.Start();

                string cmdText = cmd.ToLower();

                bool flag = false;
                switch (cmdText)
                {
                    case Constant.EXIT_CMD:
                    case Constant.Q_CMD:
                        sshClient.Disconnect();
                        break;
                    default:
                        string cmdLine = cmd;
                        bool lsAllFlag = cmd.Equals(Constant.CMD_LS_ALL);
                        bool cdFlag = cmdText.StartsWith(Constant.CMD_CD);
                        if (cdFlag)
                        {
                            CdCmd = cmd;

                            cmdLine = $"{cmd} && {Constant.CMD_PWD}";
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(CdCmd))
                            {
                                cmdLine = $"{CdCmd} && {cmd}";
                            }
                        }

                        var command = sshClient.CreateCommand(cmdLine);
                        command.CommandTimeout = TimeSpan.FromSeconds(5);

                        var result = command.BeginExecute();
                        List<string> nameList = lsAllFlag ? new List<string>() : null;
                        using (var reader = new StreamReader(command.OutputStream, Encoding.UTF8, true, 1024, true))
                        {
                            while (!result.IsCompleted || !reader.EndOfStream)
                            {
                                if (totalSencod > Constant.CMD_RUN_MAX_TIME)
                                {
                                    break;
                                }

                                string line = reader.ReadLine();
                                if (string.IsNullOrEmpty(line))
                                {
                                    continue;
                                }

                                if (lsAllFlag)
                                {
                                    if (!(line.Equals(Constant.NAME_P) || line.Equals(Constant.NAME_PP)))
                                    {
                                        nameList.Add(line);
                                    }
                                }

                                if (showMsg)
                                {
                                    SendMsg(line);
                                }
                            }
                        }

                        command.EndExecute(result);

                        timer.Stop();
                        totalSencod = 0;

                        if (showMsg)
                        {
                            if (!string.IsNullOrEmpty(command.Error))
                            {
                                SendMsg(command.Error);
                                flag = false;
                            }

                            if (!string.IsNullOrEmpty(command.Result))
                            {
                                SendMsg(command.Result);
                            }
                        }

                        if (cdFlag)
                        {
                            Run(Constant.CMD_LS_ALL, false);
                        }

                        if (lsAllFlag)
                        {
                            SaveNameList(nameList);
                        }

                        flag = true;
                        break;
                }
                return flag;
            }
            catch (Exception ex)
            {
                LogUtil.Instance.Error($"运行命令失败 - {cmd}");
                LogUtil.Instance.Error(ex);
                return false;
            }
        }

        public List<string> GetNameList()
        {
            string key = CdCmd;

            if (string.IsNullOrEmpty(key))
            {
                return null;
            }

            nameMap.TryGetValue(key, out List<string> list);

            return list;
        }

        private void SaveNameList(List<string> nameList)
        {
            string key = CdCmd;

            if (string.IsNullOrEmpty(key))
            {
                return;
            }

            if (nameMap.ContainsKey(key))
            {
                nameMap.TryRemove(key, out List<string> _);
            }

            nameMap.TryAdd(key, nameList);
        }

        private void SendMsg(string msg)
        {
            WeakReferenceMessenger.Default.Send(new NewMsgOutputMessage(Code, msg));
        }

        private void InitTimer()
        {
            timer = new Timer
            {
                Enabled = true,
                Interval = 1000,
                AutoReset = true
            };

            timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            totalSencod++;
        }

        public void Dispose()
        {
            sshClient?.Disconnect();
            ftpClient?.Disconnect();

            sshClient?.Dispose();
            ftpClient?.Dispose();
        }
    }
}
